import requests
import re
import os
import configparser
import time
import random
import urllib3
from bs4 import BeautifulSoup
import lxml

# requests设置verify=False，控制台输出InsecureRequestWarning取消方法
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
s = requests.session()
config = configparser.ConfigParser()


class Discuz:
    def __init__(self):
        self.bbsurl = ''
        self.username = ''
        self.pwd = ''
        self.fid = ''
        self.page = 1
        self.allpage = ''
        self.pageoneremove = 8
        self.timesleep = 0
        self.listlen = ''
        self.getpagecon = ''
        self.login_sccuess = ''
        print('本软件目前支持的论坛有：zygx8 || ... 完善ing \n')
        if os.path.exists('config.ini') is True:
            fix = input('是否要重新配置信息 是->1 否->输入任意数字\n: ')
            if int(fix) == 1:
                self.config()
            else:
                config.read('config.ini')
                self.bbsurl = config.get("domain", "url")
                self.username = config.get("login", "username")
                self.pwd = config.get("login", "pwd")
                self.fid = config.get("fid", "fid")
                self.page = config.get("list", "page")
                self.pageoneremove = config.get("list", "pageoneremove")
                self.timesleep = config.get("list", "timesleep")
        else:
            self.config()

        self.login()

    def config(self):
        self.bbsurl = input('bbs url:  (such as:https://www.xxxx.com/ || 本论坛直接打1):')
        if self.bbsurl== '1':
            self.bbsurl = 'https://www.zygx8.com/'
            print(self.bbsurl)
        self.username = input('username:')
        self.pwd = input('pwd:')
        self.fid = input('fid:')
        self.page = input('需要完成的page(若所有page请输入1):')
        self.pageoneremove = input('第一页需要剔除前几篇帖子？：')
        self.timesleep = input('每篇帖子之间回复延迟 单位（s）：')
        config.add_section("login")
        config.set("login", "username", self.username)
        config.set("login", "pwd", self.pwd)
        config.add_section("fid")
        config.set("fid", "fid", self.fid)
        config.add_section("list")
        config.set("list", "page", self.page)
        config.set("list", "pageoneremove", self.pageoneremove)
        config.set("list", "timesleep", self.timesleep)
        config.add_section("domain")
        config.set("domain", "url", self.bbsurl)
        config.write(open('config.ini', "w"))

    def login(self):
        login_url = self.bbsurl + 'member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1'
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'
        }
        data = {
            'fastloginfield': 'username',
            'username': self.username,
            'password': self.pwd,
            'quickforward': 'yes',
            'handlekey': 'ls'
        }
        self.login_sccuess=s.post(url=login_url, headers=headers, data=data, verify=False).text

    def getlist(self):
        list_url = self.bbsurl + 'forum.php?mod=forumdisplay&fid=' + str(self.fid) + '&page=' + str(self.page)
        # print(list_url)
        list_res = s.get(url=list_url, verify=False)
        self.getpagecon = list_res.text
    def gettid(self):
        self.getlist()
        soup=self.getpagecon
        list1 = self.getpagecon
        r = int(self.pageoneremove)
        p = int(self.page)
        if p == 1:
            self.listlen = len(list1[r:])
            list1 = str(list1[r:])
        else:
            self.listlen = len(list1)
            list1 = str(list1)
        list1 = re.findall(r'tid=.*?&', list1)
        with open('list.txt', 'w', encoding='utf8') as f:
            for i in list1:
                f.write(i + '\n')

    def getformhash(self):
        self.getlist()
        pageformhash = self.getpagecon
        pageformhash = re.findall(r'formhash=.*?">退出', self.getpagecon)
        pageformhash = str(pageformhash).replace('[\'formhash=', '').replace('">退出\']', '')
        return pageformhash

    def getallpage(self):
        self.getlist()
        allpages=re.findall(r'共 . 页',self.getpagecon)
        allpages=allpages[0]
        allpages=allpages.replace('共', '').replace('页', '').strip()
        return allpages

    def replay(self):
        print('请确认fid:' + self.fid + '和tid是对应关系，即将开始逐个回复...')
        hurls = self.bbsurl + 'forum.php?mod=post&action=reply&fid=' + str(self.fid) + '&'
        eurls = 'extra=&replysubmit=yes&infloat=yes&handlekey=fastpost&inajax=1'
        formhash = self.getformhash()
        massage = [
            '666666666',
            '777777777',
            '888888888',
            '999999999',
            '111111111',
        ]
        data = {
            'select': '',
            'message': massage[random.randint(0, 4)],
            'posttime': str(int(time.time())),
            'formhash': formhash,
            'usesig': '',
            'subject': ''
        }

        with open('list.txt', 'r', encoding='utf8') as f:
            for tid in f.readlines():
                reply_url = hurls + tid.strip('\n') + eurls
                rep = s.post(url=reply_url, data=data)
                if '成功' in rep.text:
                    print('本次回复帖子' + tid.strip('\n') + '成功')
                else:
                    print('本次回复帖子' + tid.strip('\n') + '失败 ，原因自查')
                time.sleep(int(self.timesleep))


if __name__ == '__main__':
    d = Discuz()
    print('******欢迎使用******')
    print('******功能1： ******')
    print('******1：单页 自动抓tid回贴 ******')
    print('******功能2： ******')
    print('******2：自定义tid回贴 请按照 tid= + 数字 + & （如：tid=18102&）的格式保存在list.txt中******')
    print('******功能3： ******')
    print('******3：一个版块下所有页的帖子 回帖 ******\n\n')
    if 'window.location.href' in d.login_sccuess:
        print('账号密码正确 starting')
        fun = input('******* 请 选 择 功 能 *******\n:')
        if int(fun) == 1:
            print('***开始自动抓tid回贴 记得注意fid值噢***')
            d.gettid()
            all_time=(d.listlen*int(d.timesleep))/60
            print('预计需要'+str(int(all_time))+'分完成')
            d.replay()
        elif int(fun) == 2:
            print('***开始自定义tid回贴 记得注意fid值噢***')
            d.replay()
        elif int(fun) == 3:
            all_page=d.getallpage()
            print('获取到',all_page,'页')
            for i in range(int(all_page)):
                d.page=i+1
                print('第', i + 1, '页 开始')
                d.gettid()
                d.replay()
                print('第',i+1,'页 完成')
    else:
        print('账号密码错误 请手动打开运行目录下的config.ini文件修改密码或者删除该文件 然后重新运行本程序！')


#整理 一个通用的 gettid 方法 ：修改正则表达式
    #exit=input('程序运行完成，输入任意建退出')
